﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;

namespace AFT.Parking.Foundation.Extensions
{
    public static class Serialization
    {
        /// <summary>
        /// 对象序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="TModel"></param>
        /// <returns></returns>
        public static string Serialize<T>(this T  TModel)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            formatter.Serialize(ms, TModel);
            ms.Seek(0, SeekOrigin.Begin);
            byte[] bt = new byte[ms.Length];
            ms.Read(bt, 0, bt.Length);
            ms.Close();
            ms.Dispose();
            return Convert.ToBase64String(bt);
        }

        /// <summary>
        /// 对象序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="TModel"></param>
        /// <returns></returns>
        public static string SerializeXml<T>(this T TModel)
        {
            using (StringWriter sw = new StringWriter())
            {
                XmlSerializer xz = new XmlSerializer(TModel.GetType());
                xz.Serialize(sw, TModel);
                return sw.ToString();
            }
        }

        /// <summary>
        /// 反序化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strBase64"></param>
        /// <returns></returns>
        public static T Deserialize<T>(this string strBase64)
        {
            T obj = default(T);
            try
            {
                IFormatter formatter = new BinaryFormatter();
                byte[] bt = System.Convert.FromBase64String(strBase64);
                MemoryStream ms = new MemoryStream(bt);
                obj = (T)formatter.Deserialize(ms);
                ms.Close();
                ms.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return obj;
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="s"></param>
        /// <returns></returns>
        public static object DeserializeXml(Type type, string s)
        {
            using (StringReader sr = new StringReader(s))
            {
                XmlSerializer xz = new XmlSerializer(type);
                return xz.Deserialize(sr);
            }
        }
    }
}
